<template>
  <div>
    <div class="uploader" v-show="showUploader" @click="showUploader = false">
      <div>
        <div class="ub ub-ac">从手机中选择</div>
        <form enctype="multipart/form-data" id="add_form" method="post" name="uploadImg">
          <input type="file" @change="onFileChange" name="uploadFile" accept="image/*">
        </form>
      </div>
    </div>
    <div class="bg_f2 fc_333" v-show="userModify.userInfo.userId">
      <div class="ub ub-ver bg_w">
        <div class="ub ub-pj pad_1">
          <div class="ub ub-ac">头像</div>
          <div class="ub userPlace" @click="showUploader = true">
            <div v-show="!userModify.userInfo.userIcon" class="userIcon ub-img1"></div>
            <div v-show="userModify.userInfo.userIcon" style="width:100%;height:100%">
              <img :src="userModify.userInfo.userIcon" style="width:100%;height:100%;border-radius:50%;">
            </div>
          </div>
        </div>
        <div class="ub ub-pj pad_1">
          <div class="ub">手机号</div>
          <div class="ub">{{userModify.userInfo.userMobile}}</div>
        </div>
        <div class="ub ub-pj pad_1">
          <div class="ub">修改密码</div>
          <div class="ub">
            <div class="ub ub-ac fc_purple" @click="$router.push('/modifyPWD')">修改</div>
            <div class="ub rightA ub-img1"></div>
          </div>
        </div>
      </div>
      <div class="ub ub-ver bg_w mar_t1">
        <div class="ub ub-ac pad_1 ub-ver" @click="modifyClc(0)">
          <div class="ub ub-pj wd_100 pad_b05">
            <div class="ub">
              <div class="ub ub-ac">真实姓名</div>
            </div>
            <div class="ub ub-ac ">
              <div class="ub ub-ac ub-pc">{{userModify.userInfo.userLinkMan}}</div>
              <div class="ub rightA ub-img1"></div>
            </div>
          </div>
          <div class="line"></div>
        </div>
        <div class="ub ub-ac pad_1 ub-ver" @click="modifyClc(1)">
          <div class="ub ub-pj wd_100 pad_b05">
            <div class="ub">
              <div class="ub ub-ac">证件号码</div>
            </div>
            <div class="ub ub-ac ">
              <div class="ub ub-ac ub-pc">{{userModify.userInfo.userLinkNumber}}</div>
              <div class="ub rightA ub-img1"></div>
            </div>
          </div>
          <div class="line"></div>
        </div>
        <div class="ub ub-ac pad_1 ub-ver" @click="modifyClc(2)">
          <div class="ub ub-pj wd_100 pad_b05">
            <div class="ub">
              <div class="ub ub-ac">联系电话</div>
            </div>
            <div class="ub ub-ac ">
              <div class="ub ub-ac ub-pc">{{userModify.userInfo.userLinkPhone}}</div>
              <div class="ub rightA ub-img1"></div>
            </div>
          </div>
          <div class="line"></div>
        </div>
        <div class="ub ub-ac pad_1 ub-ver" @click="modifyClc(3)">
          <div class="ub ub-pj wd_100 pad_b05">
            <div class="ub">
              <div class="ub ub-ac">联系邮箱</div>
            </div>
            <div class="ub ub-ac ">
              <div class="ub ub-ac ub-pc">{{userModify.userInfo.userLinkEmail}}</div>
              <div class="ub rightA ub-img1"></div>
            </div>
          </div>
          <div class="line"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
import { mapState } from 'vuex';
// import $ from '../../../static/dateScroll/jquery.min.js';
import $ from '../../../static/dateScroll/jquery-1.9.1.js';
// const typeArr = [
//   {
//     name: '真实姓名',
//     propStr: 'userLinkMan'
//   },
//   {
//     name: '证件号码',
//     propStr: 'userLinkNumber'
//   },
//   {
//     name: '联系电话',
//     propStr: 'userLinkPhone'
//   },
//   {
//     name: '联系邮箱',
//     propStr: 'userLinkEmail'
//   }
// ];
export default {
  name: 'userInfo',
  created: function () {
    this.$store.commit('changeHeader', {
      left: '返回',
      right: '',
      middle: '账号资料',
      ifshow: true,
      leftAction: '-1',
      leftIcon: 'leftIcon',
      rightAction: '',
      rightIcon: ''
    });
    /* if (!this.userModify.ifFresh) {
      return false
    } */
    this.initUserInfo();
    // this.$store.commit('showLoading');
    // this.$http.post(this.$RS.searchInfo, data).then(
    //   function (res) {
    //     // 响应成功回调
    //     this.$store.commit('closePop');
    //     res = res.body
    //     console.log(res);
    //     if (res.code === 1000) {
    //       console.log('in');
    //       // this.$store.dispatch('showTx', { text: res.message })
    //       let resInfo = res.content;
    //       this.$store.commit('setUserInfo', resInfo);
    //       // this.$store.commit('setChangeData', resInfo);
    //       this.$store.commit('setFresh', false);
    //     } else {
    //       console.log('out');
    //       this.$store.commit('closePop');
    //       this.$store.dispatch('showTx', { text: res.message });
    //       this.$router.go(-1);
    //     }
    //   },
    //   function (err) {
    //     // 响应错误回调
    //     this.$store.dispatch('showTx', { text: err.message || '网络错误，请重试' });
    //   }
    // );
  },
  data: function () {
    return {
      showUploader: false,
      imageUrl: '',
      size: ''
    };
  },
  methods: {
    getProsValue: function (str) {
      console.log(this)
      return this[str];
    },
    modifyClc: function (type) {
      console.log('click');
      // const typeArr = ['userLinkMan', 'userLinkNumber', 'userLinkPhone', 'userLinkEmail']
      this.$store.commit('setModify', type);
      this.$router.push('/userModify');
    },
    onFileChange: function (e) { // 触发上传头像事件
      let files = e.target.files || e.dataTransfer.files;
      console.log(files);
      if (!files.length) {
        return false;
      }
      // this.createImage(files[0]);
      this.size = files[0].size;
      this.uploadImg(files);
    },
    createImage: function (file) {
      let self = this;
      let reader = new FileReader();
      reader.onload = function (event) {
        let blob = new Blob([event.target.result]);
        window.URL = window.URL || window.webkitURL;
        let blobURL = window.URL.createObjectURL(blob);
        let image = new Image();
        image.src = blobURL;
        image.onload = function () {
          let resizedImg = self.resizeImg(image);
          resizedImg = self.convertToBinary(resizedImg);
          self.doImgAjax(resizedImg);
          // compressValue.value = resized;
        }
      };
      reader.readAsArrayBuffer(file[0]);
    },
    resizeImg: function (data) {
      console.log(data);
      let compressionRatio = 1024 * 1024 / (this.size || (10 * 1024 * 1024));
      console.log('compressionRatio:' + compressionRatio);
      let cvs = document.createElement('canvas');
      let ctx = cvs.getContext('2d');
      // let img = new window.Image()
      // img.src = data;
      // img.onload = () => {
      cvs.width = data.width;
      cvs.height = data.height;
      // setTimeout(() => {
      ctx.drawImage(data, 0, 0, cvs.width, cvs.height)
      let newImageData = cvs.toDataURL('image/jpeg', compressionRatio);
      console.log(newImageData.length);
      // }, 0)
      // this.showPreviewer = true
      // }
      // console.log('newImageData');
      // console.log(newImageData);
      return newImageData;
    },
    uploadImg: function (data) {
      // let file = data[0];
      if (data[0].size >= 1024 * 1024) { // 图片尺寸超过1M
        // if (data[0].size < 1024 * 1024) { // 测试
        this.$store.commit('showLoading');
        this.createImage(data);
        return false;
      }
      this.doImgAjax(data[0]);
    },
    convertToBinary: function (dataURI) {
      let byteString = window.atob(dataURI.split(',')[1])
      let ab = new ArrayBuffer(byteString.length)
      let ia = new Uint8Array(ab)
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      let bb = new window.Blob([ab])
      return bb
    },
    doImgAjax: function (file) {
      let self = this;
      let form = new FormData();
      form.append('uploadFile', file);
      this.$store.commit('showLoading');
      $.ajax({
        url: self.$RS.uploadImg,
        type: 'POST',
        data: form,
        processData: false,
        contentType: false,
        // xhrFields: {
        //   withCredentials: true
        // },
        // crossDomain: true,
        success: function (res) {
          self.$store.commit('closePop');
          console.log(res);
          if (res.code === 1000) {
            self.$store.dispatch('showTx', { text: '上传成功' });
            self.imageUrl = res.content.key;
            self.changHeadIcon(); // 修改关联的头像地址
          } else {
            self.$store.dispatch('showTx', { text: res.message })
          }
        },
        error: function (err) {
          // alert('服务器请求失败');
          this.$store.commit('closePop');
          self.$store.dispatch('showTx', { text: err.message || '网络错误，请重试' })
        }
      });
    },
    initUserInfo: function () {
      let userInfo = this.loginData.userInfo;
      if (!userInfo) {
        this.$router.push('/login');
      }
      let userId = userInfo.userId;
      let loginToken = userInfo.token.loginToken;
      let userMobile = userInfo.userMobile;
      let content = {
        'userMobile': userMobile,
        'userId': userId
      }
      let data = this.$utils.getUserContent(content);
      data.headers.userId = userId;
      data.headers.loginToken = loginToken;
      let self = this;
      this.$utils.ajax(data, 'searchInfo', self, function (res) {
        console.log(res)
        let resInfo = res.content;
        self.$store.commit('setUserInfo', resInfo);
        // this.$store.commit('setChangeData', resInfo);
        self.$store.commit('setFresh', false);
      })
    },
    changHeadIcon: function () {
      let self = this;
      let userInfo = this.loginData.userInfo;
      if (!userInfo) {
        this.$router.push('/login');
      }
      let userId = userInfo.userId + '';
      let loginToken = userInfo.token.loginToken;
      let content = {
        'userIcon': self.imageUrl,
        'userId': userId
      }
      let data = this.$utils.getUserContent(content);
      data.headers.userId = userId;
      data.headers.loginToken = loginToken;
      this.$utils.ajax(data, 'modify', self, function () {
        self.$store.dispatch('showTx', { text: '修改成功' });
        let userInfo = self.loginData.userInfo; // 还需要设置loginData 的头像
        userInfo.userIcon = self.imageUrl;
        self.$utils.setSession('loginData', userInfo);
        window.localStorage.setItem('userIcon', self.imageUrl)
        // self.$store.commit('setLogin', {});
        // console.log('img>>>>>>>>>>>>>>>>>>>>>');
        // console.log(self.imageUrl);
        self.$store.commit('setUserIcon', self.imageUrl);
        self.initUserInfo();
      });
    }
    // createImage: function (file) {
    //   // let image = new Image();
    //   let reader = new FileReader();
    //   let self = this;

    //   reader.onload = (e) => { // 读取完成
    //     let image = e.target.result;
    //     // console.log(image);
    //     let data = {
    //       uploadFile: 'a=' + image
    //     }
    //     self.$utils.$ajax2(data, 'uploadImg', self, function (res) {
    //       console.log(res)
    //     })
    //   };
    //   reader.onerror = function () {
    //     console.log('error'); // 文件读取出错的时候触发，暂模拟不出
    //     self.showUploader = false;
    //     self.$store.dispatch('showTx', { text: '读取文件出错' });
    //   };
    //   reader.readAsDataURL(file);
    // }
  },
  computed: mapState(['loginData', 'userModify'])
}
</script>

<style lang="stylus">
@import '../../stylus/base.styl';
.userPlace
  /* border:1px solid red; */
  width: f_times(4);
  height: f_times(4);
.userIcon
  height: 100%;
  width: 100%;
  background-image: url('member_avatar_default.png');
.uploader
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  >div
    height: f_times(3);
    width: 90%;
    background-color: #fff;
    border-radius: 5px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -(@height / 2);
    margin-left: -(@width / 2);
    input
      width: 100%;
      height: 100%;
      opacity: 0;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 2000;
    >div
      position: absolute;
      left: 50%;
      top: 50%;
      height: f_times(1.5);
      // width:100%;
      // height:100%
      margin-top: -(@height / 2);
      margin-left: -(@width / 2);
      z-index: 2000;
</style>